﻿using System;
using Tolo.SimplePG.Permissions;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Tolo.SimplePG.Services.Dtos.Books;
using Tolo.SimplePG.Entities.Books;

namespace Tolo.SimplePG.Services.Books;

public class BookAppService :
    CrudAppService<
        Book, //The Book entity
        BookDto, //Used to show books
        Guid, //Primary key of the book entity
        PagedAndSortedResultRequestDto, //Used for paging/sorting
        CreateUpdateBookDto>, //Used to create/update a book
    IBookAppService //implement the IBookAppService
{
    public BookAppService(IRepository<Book, Guid> repository)
        : base(repository)
    {
        GetPolicyName = SimplePGPermissions.Books.Default;
        GetListPolicyName = SimplePGPermissions.Books.Default;
        CreatePolicyName = SimplePGPermissions.Books.Create;
        UpdatePolicyName = SimplePGPermissions.Books.Edit;
        DeletePolicyName = SimplePGPermissions.Books.Delete;
    }

    public virtual async Task<List<BookDto>> GetAllListAsync(GetBookInput input)
    {
        var query = await ReadOnlyRepository.GetQueryableAsync();
        query = query.WhereIf(!input.AuthorName.IsNullOrWhiteSpace(), t => t.Author.Name.Contains(input.AuthorName)).
                      WhereIf(!input.PublisherName.IsNullOrWhiteSpace(), t => t.Publisher.Name.Contains(input.PublisherName));
        var entitys = await AsyncExecuter.ToListAsync(query);

        return ObjectMapper.Map<List<Book>, List<BookDto>>(entitys);
    }
}